﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GanagroLiteBO;
using System.Globalization;
using GLiteInterfaces;

namespace GanagroLite
{
    public partial class FormVentas : FormOperaciones
    {
         private ModoForma mForma = ModoForma.inicializando;
         private bool _modoConsulta = false;

        #region Constructor
        public FormVentas( bool modoConsulta)
        {
            InitializeComponent();
            this.bindingSourceMain.DataSource = new Pesajes();
            currentNota = new NotaBO(TiposOperacion.venta);
            this.bindingSourceNota.DataSource = currentNota;
            _modoConsulta = modoConsulta ;
        }
        #endregion Constructor

        #region Internal methods

        protected internal override object GetIdValue()
        {
            return "Vender Semovientes" + _modoConsulta.ToString();
        }

        public override string ToString()
        {
            return "Vender Semovientes";
        }

        #endregion

        #region DataBinding methods
        private void bindingSourceMain_AddingNew(object sender, AddingNewEventArgs e)
        {
            //currentNota.Fecha = Convert.ToDateTime(this.dtPickerFecha.Text).Date;
            //currentNota.Nota = this.textBoxNota.Text;
            //currentNota.TipoOperacion = TiposOperacion.venta;

            List<string> nuevoscodigos = (from p in (Pesajes)this.bindingSourceMain.DataSource select p.CODIGO).ToList<string>();


            e.NewObject = new PESAJES_BO(nuevoscodigos, currentNota, GetPrecioKilo());

        }


        private Int32 GetPrecioKilo()
        {
            Int32 precioKilo = 0;
            NumberStyles styles = NumberStyles.Integer | NumberStyles.AllowThousands;
            Int32.TryParse(this.textBoxPrecio.Text, styles, CultureInfo.InvariantCulture, out precioKilo);

            return precioKilo;
        }

        private void bindingSourceMain_PositionChanged(object sender, EventArgs e)
        {
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);
        }

        #endregion

        #region UI handlers


        private void dtPickerFecha_Validated(object sender, EventArgs e)
        {
            try
            {
                if (mForma == ModoForma.cargada)
                    this.bindingSourceMain.ResetBindings(true);

                currentNota.Fecha = Convert.ToDateTime(dtPickerFecha.Text).Date;
                currentNota.Cargar();

                this.errorProviderNotasFecha.SetError(dtPickerFecha, currentNota.Error);
                this.WarningProviderNotas.SetError(dtPickerFecha, currentNota.Warnings());

                btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);

                if (this.bindingSourceMain.Count > 0)
                {
                    ((Pesajes)this.bindingSourceMain.DataSource).Setfecha(Convert.ToDateTime(dtPickerFecha.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void textBoxNota_Validated(object sender, EventArgs e)
        {
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid() && (bindingSourceMain.Count > 0);
        }

        private void textBoxNota_TextChanged(object sender, EventArgs e)
        {
            buttonNota.Enabled = !string.IsNullOrEmpty(textBoxNota.Text.Trim());
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);
        }

        private void buttonGuardarNota_Click(object sender, EventArgs e)
        {
            try
            {
                base.GuardarNota();
            }
           catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private async void buttonRefrescar_Click(object sender, EventArgs e)
        {
            var cColor = buttonRefrescar.ForeColor;
            buttonRefrescar.ForeColor = Color.DarkGoldenrod;

            lblTotalVentas.Text = "...";

            if (((Pesajes)this.bindingSourceMain.DataSource).Count > 0 && ((Pesajes)this.bindingSourceMain.DataSource).Any(p => p.IsValid(true) == true))
            {
                var t1 =  Task<string>.Run(() => ((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid() == true).Count().ToString());
                var t2 = Task<string>.Run(() => ((int)((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid(true) == true).Average(p => p.DiasUltPesaje)).ToString() + " dias.");
                var t3 = Task<string>.Run(() => ((int)((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid(true) == true).Average(p => p.UltimaGanancia)).ToString() + " grs.");
                var t4  = Task<string>.Run(() => ((int)((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid(true) == true).Average(p => p.Diasvida)).ToString() + " dias.");
                var t5  = Task<string>.Run(() => ((int)((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid(true) == true).Average(p => p.GananciaVida)).ToString() + " grs.");
                var t6 = Task<Int32>.Run(() => (Int32)((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid(true) == true).Sum(p => (p.Peso * p.VALOR2))); 

                lblregCount.Text = await t1;
                lblDiasUltPesaje.Text = await t2;
                lblUltGanancia.Text = await t3;
                lblDiasVida.Text = await t4;
                lblGananciaVida.Text = await t5;

                Int32 total = await t6;
                this.lblProm.Text = String.Format("{0:0.0}", ((Pesajes)this.bindingSourceMain.DataSource).Where(p => p.IsValid(true) == true).Average(wp => wp.Peso));

                lblTotalVentas.Text = string.Format("{0:###,###,###}", total);
            }

            buttonRefrescar.ForeColor = cColor;
        }

        private void dataGridViewMain_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            if ((PESAJES_BO)bindingSourceMain.Current == null)
            {
                return;
            }

//            bindingSourceMain.EndEdit();

            if (e.ColumnIndex == 1)
            {
                switch (((PESAJES_BO)bindingSourceMain.Current).CalidadUltimaGanancia)
                {
                    case TiposGananciaDiaria.Buena:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.Green;
                        break;
                    case TiposGananciaDiaria.Regular:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.DarkOrange;
                        break;
                    case TiposGananciaDiaria.Perdida:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.Red;
                        break;
                    case TiposGananciaDiaria.Erronea:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.DarkOrchid;
                        break;
                    default:
                        break;
                }

                switch (((PESAJES_BO)bindingSourceMain.Current).CalidadGananciaVida)
                {
                    case TiposGananciaDiaria.Buena:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.Green;
                        break;
                    case TiposGananciaDiaria.Regular:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.DarkOrange;
                        break;
                    case TiposGananciaDiaria.Perdida:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.Red;
                        break;
                    case TiposGananciaDiaria.Erronea:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.DarkMagenta;
                        break;
                    default:
                        break;
                }

                dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].ToolTipText = ((PESAJES_BO)bindingSourceMain.Current).FechaPesajePrevio.ToShortDateString();
                dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].ToolTipText = ((PESAJES_BO)bindingSourceMain.Current).FechaPrimerPesaje.ToShortDateString();
            }
        }

        private void textBoxPrecio_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != 8)
            {
                // Consume this invalid key and beep
                e.Handled = true;
            }

        }

        private void dataGridViewMain_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            try
            {
                GLiteBO gbo = new GLiteBO(dataGridViewMain[0, e.RowIndex].Value.ToString());
                if (gbo.IsValid())
                {
                    this.contextMenuStrip1.AutoSize = true;
                    this.contextMenuStrip1.Items.Clear();
                    this.contextMenuStrip1.Items.Add("Pesajes anteriores:");
                    foreach (string str in gbo.ListaPesajes())
                    {
                        this.contextMenuStrip1.Items.Add(str);
                    }
                }
            }
            catch
            {
            }

        }

        private void dtPickerFecha_Validating(object sender, CancelEventArgs e)
        {
            DateTime dt;

            this.errorProviderNotasFecha.SetError(dtPickerFecha, string.Empty);

            if (DateTime.TryParse(dtPickerFecha.Text, out dt) == false)
            {
                this.errorProviderNotasFecha.SetError(dtPickerFecha, "Formato de fecha invalido");
                e.Cancel = true;
            }

            if (dt > DateTime.Now)
            {
                this.errorProviderNotasFecha.SetError(dtPickerFecha, "La fecha no puede ser en el futuro");
                e.Cancel = true;
            }
        }

        private void textBoxPrecio_Validated(object sender, EventArgs e)
        {
            try
            {
                short precio = 0;
                NumberStyles styles = NumberStyles.Integer | NumberStyles.AllowThousands;
                this.dataGridViewMain.Enabled = short.TryParse(this.textBoxPrecio.Text, styles, CultureInfo.InvariantCulture, out precio);

                btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(false) && (bindingSourceMain.Count > 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {

            Cursor cCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

            try
            {
                bindingSourceMain.SuspendBinding();

                string errorMessages = string.Empty, infoMessages = string.Empty;
                string ultimoCodigo = string.Empty;

                if (GuardarNota() == false)
                {
                    return;
                }

                Ventas V = new Ventas();

                foreach (var item in (BindingListView<PESAJES_BO>)bindingSourceMain.DataSource)
                {
                    V.Add(new VentaBO(item,GetPrecioKilo()));
                }

                utilities.Guardar_View<VentaBO>(V, ref infoMessages, ref errorMessages, ref ultimoCodigo,false);

                if (errorMessages.Length > 0)
                {
                    MessageBox.Show(errorMessages, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                //MessageBox.Show(infoMessages, "Informacion", MessageBoxButtons.OK, MessageBoxIcon.Information);

                ((IOperacionView)this).status2 = infoMessages;

                this.bindingSourceMain.ResumeBinding();

                ((BindingListView<PESAJES_BO>)bindingSourceMain.DataSource).Clear();

                this.status = string.Format("Ultimo codigo procesado: {0}", ultimoCodigo);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.lblDiasUltPesaje.Text = this.lblDiasVida.Text = this.lblGananciaVida.Text =
                this.lblUltGanancia.Text = this.lblregCount.Text = "0";
                System.Windows.Forms.Cursor.Current = cCursor;
            }

        }

        private void buttonSalir_Click(object sender, EventArgs e)
        {
            if (confirmaSalir(bindingSourceMain.Count) == false)
            { return; }

            this.bindingSourceMain.CancelEdit();
            this.bindingSourceNota.CancelEdit();
            this.status = string.Empty;

            this.Close();

        }

        private void dataGridViewMain_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 0 || e.ColumnIndex == 1)
                {
                    //GANADO_BO bgo = new GANADO_BO(dataGridViewMain[0, e.RowIndex].Value.ToString());
                    MessageBox.Show(this, GANADO_BO.ListaPesajes(dataGridViewMain[0, e.RowIndex].Value.ToString()), "Lista de pesajes", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void dataGridViewMain_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Valor en formato Invalido");
        }

        #endregion

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }


    }
}
